<template>
  <view>
    <u-loading-page :loading="pageLoading"></u-loading-page>

    <hx-navbar ref="hxnb" :config="config" @clickBtn="clickBtn">
      <view slot="bottom">
        <template>
          <view class="input-product">
            <u-search
              placeholder="搜索"
              v-model="searchData.keywords"
              @change="onSearchChange"
              :showAction="false"
            ></u-search>
          </view>
        </template>
      </view>
    </hx-navbar>

    <scroll-view
      class=""
      scroll-y
      refresher-enabled
      show-scrollbar
      :refresher-triggered="triggered"
      @refresherrefresh="$u.throttle(onRefresherrefresh, 200)"
      @scrolltolower="$u.throttle(onScrolltolower, 1000)"
      :style="{ height: `${screenHeight}px`, paddingTop: '60px' }"
    >
      <u-empty
        mode="list"
        v-if="listData.length == 0"
        :style="{ height: `${screenHeight}px` }"
      />
      <!-- 列表 -->
      <view class="view p-l-10 p-r-10">
        <view class="item-box" v-for="(item, index) in listData" :key="index">
          <u-avatar
            shape="square"
            @click="avatarClick(item, index)"
            style="
              width: auto;
              padding: 0 20rpx;
              height: 48rpx;
              border-radius: 0;
            "
            :text="item.name"
            fontSize="12"
            :randomBgColor="item.active"
          ></u-avatar>
          <view class="del" v-if="isEdit" @click="onDel(item)"> X </view>
        </view>
      </view>
    </scroll-view>

    <u-modal
      :show="addShow"
      title="添加标签"
      @confirm="addLabelConfirm"
      @cancel="addShow = false"
      @close="addShow = false"
      showCancelButton
      confirmText="保存"
    >
      <u--input
        placeholder="请输入内容"
        border="surround"
        v-model="addValue"
      ></u--input>
    </u-modal>

    <!-- 删除 -->
    <u-modal
      :show="isDel"
      showCancelButton
      :closeOnClickOverlay="true"
      @close="isDel = false"
      @cancel="isDel = false"
      @confirm="onConfirm"
    >
      <view class="slot-content"
        >你确定要删除<text v-if="name">【{{ name }}】</text>吗？
      </view>
    </u-modal>
  </view>
</template>

<script>
import _ from "lodash";
import {
  getlabelForCustomerData,
  lableAddOrUpdateList,
  lableDeleteById,
} from "@/apis/bill/information/custom";
export default {
  data() {
    return {
      searchData: {},
      screenHeight: 0,
      pageLoading: true,
      triggered: false,
      listData: [],
      pageInfo: {
        current: 1, // 当前页
        size: 100, // 每页数据条数
        sort: "", // 排序字段
        order: "desc", // 排序方向
        total: 0, // 总数居量
      },
      config: {
        title: "选择标签",
        color: "#ffffff",
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "&#xe68d;",
            position: "left",
          },
          {
            key: "btn2",
            icon: "&#xe727;",
            position: "left",
          },
        ],
      },
      addShow: false,
      addValue: "",
      isEdit: false,
      isDel: false,
      name: "",
      id: null,
      arrList: [],
    };
  },
  onLoad(opt) {
    if (opt && opt.item) {
      this.arrList = opt.item;
    }
    this.initData();
  },
  onReady() {
    const sysInfo = uni.getSystemInfoSync();
    this.screenHeight = sysInfo.windowHeight;
  },
  methods: {
    delete() {
      lableDeleteById(this.id)
        .then((res) => {
          if (!res.flag) return;
          this.listPage();
        })
        .finally((_) => {});
    },
    // 新增标签
    addLabelConfirm() {
      let arr = this.listData;
      arr.push({ name: this.addValue, remarks: "" });
      lableAddOrUpdateList(arr)
        .then((res) => {
          if (!res.flag) return;
        })
        .finally((_) => {});
      this.addValue = "";
      this.addShow = false;
      this.listPage();
    },
    // 点击当前删除选择
    avatarClick(item, index) {
      if (!item.active) {
        this.listData[index].active = true;
      } else {
        this.listData[index].active = !item.active;
      }
      const filteredData = this.listData
        .filter((item) => item.active === true)
        .map((item) => {
          item.labelName = item.name;
          item.labelId = item.id;
          return item;
        });
      uni.$emit("on-lable-page", filteredData);
      this.$forceUpdate();
    },
    initData() {
      this.listPage();
    },
    listPage() {
      const params = {
        page: this.pageInfo,
        data: this.searchData,
      };
      uni.showLoading({
        title: "加载中",
      });
      getlabelForCustomerData(params)
        .then((res) => {
          if (!res.flag) return;
          const records = res.data || [];
          this.listData = records;
          this.listData.forEach((item) => {
            item.active = this.arrList.some(
              (listItem) => item.id === listItem.labelId
            );
          });
        })
        .finally((_) => {
          this.triggered = false;
          this.pageLoading = false;
          uni.hideLoading();
        });
    },
    onSearchChange() {
      this.handlerSearch();
    },
    handlerSearch: _.debounce(function () {
      this.listData = [];
      this.listPage();
    }, 200),
    itemClick(row) {
      uni.$emit("on-emergency-degree", row);
      this.$Router.back();
    },
    onRefresherrefresh() {
      this.triggered = true;
      this.listData = [];
      this.listPage();
    },
    onScrolltolower() {},
    clickBtn(item) {
      if (item.key === "btn2") {
        this.addShow = !this.addShow;
      } else {
        this.isEdit = !this.isEdit;
      }
    },
    onDel(val) {
      this.isDel = true;
      this.name = val.name;
      this.id = val.id;
    },
    onConfirm() {
      this.isEdit = false;
      this.isDel = false;
      this.delete();
    },
  },
};
</script>

<style lang="scss" scoped>
.view {
  display: flex;
  flex-wrap: wrap;
}

.input-product {
  width: 95%;
  margin: 20upx auto;
  border-radius: 50upx;
  height: 70upx;
  line-height: 70upx;
  color: #fff;
}
.item-box {
  position: relative;
  padding: 10rpx;
  margin-right: 20rpx;
  .del {
    background-color: #f00;
    font-size: 24rpx;
    display: inline-block;
    width: 30rpx;
    height: 30rpx;
    text-align: center;
    line-height: 30rpx;
    border-radius: 100%;
    color: #fff;
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
